//permutation of string

#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;



int permutation3(string s, const string cs, bool used[],int num) //better
{
  static int c =0;//count of recursive call
  c++;
  static int count =0 ;
 
//recursive case
  for(int i = 0;i<(int)cs.length();i++) {
    if(used[i] == false){ //find the first unused char
      if (s.length() == (unsigned int)(num - 1) ) { //base case
	count++;
	cout<<count<<"\t"<<s + cs[i]<<endl;
// 	return c;
      }
      else { //recursive case
	used[i] = true;
	permutation3(s+cs[i],cs,used,num);
	used[i] = false;
      }
    
    }
  }//for
  return c;
}

int main(int argc, char *argv[])
{
  string cs;
  int num;
  if(argc == 3){
    cs = argv[1];
    num = atoi(argv[2]);
  }
  else if(argc == 2){
    cs = argv[1];
    num = cs.length();
  }
  else {
    cs = "abcd";
    num = 4;
  }
  bool used[cs.length()];
  for(int i = 0;i<(int)cs.length();i++){
    used[i] = false;
  }
  int c = permutation3("",cs,used,num);
  cout<<"#recursive calls is \t"<<c<<endl;


  return 0;
}
